# 构建阶段
FROM python:3.9-slim as builder

WORKDIR /app
COPY requirements.txt .

RUN pip install --user --no-cache-dir -r requirements.txt

# 运行阶段
FROM python:3.9-slim

WORKDIR /app

# 从构建阶段复制已安装的Python包
COPY --from=builder /root/.local /root/.local
COPY . .

# 设置环境变量
ENV PATH=/root/.local/bin:$PATH \
    PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    FLASK_ENV=production

# 安装系统依赖
RUN apt-get update && \
    apt-get install -y --no-install-recommends curl && \
    rm -rf /var/lib/apt/lists/*

# 确保脚本可执行
RUN chmod +x app.py temperature_collector.py

# 创建数据目录
RUN mkdir -p /data/data_temp && \
    chmod 777 /data/data_temp

# 健康检查
HEALTHCHECK --interval=30s --timeout=3s \
    CMD curl -f http://localhost:5000/ || exit 1

# 暴露端口
EXPOSE 5000

# 设置非root用户
RUN useradd -m appuser && \
    chown -R appuser:appuser /app && \
    chown -R appuser:appuser /data/data_temp

USER appuser

# 设置启动命令
CMD ["python", "app.py"]